package DetailedLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @projectName: JUC
 * @package: DetailedLock
 * @className: spinlocks
 * @author: 冷环渊 doomwatcher
 * @description: TODO 实现自旋锁
 * @date: 2022/3/5 2:25
 * @version: 1.0
 */
public class spinlocks {
    //    int =0
//    thread = null
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    //    加锁操作
    public void mylock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "=> mylock");
        while (!atomicReference.compareAndSet(null, thread)) {
        }
    }

    //    解锁
    public void myunlock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "=> myUnlock");
        atomicReference.compareAndSet(thread, null);
    }
}

class test {
    public static void main(String[] args) throws InterruptedException {
        //底层使用 CAS 自旋锁
        spinlocks lock = new spinlocks();
        new Thread(() -> {
            lock.mylock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myunlock();
            }
        }, "t1").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            lock.mylock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myunlock();
            }
        }, "t2").start();
    }
}
